package com.handy.easy.admin.service.impl.jap;

import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fujieid.jap.core.JapUser;
import com.fujieid.jap.core.JapUserService;
import com.fujieid.jap.spring.boot.common.JapUserServiceType;
import com.handy.easy.admin.constants.BaseConstants;
import com.handy.easy.admin.constants.enums.LoginSourceEnum;
import com.handy.easy.admin.mapper.SysUserAccountMapper;
import com.handy.easy.admin.model.sys.SysUserAccount;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * jap-simple 是为了方便快速的集成本地账号密码登录而添加的增强包
 *
 * @author handy
 */
@Service(JapUserServiceType.SIMPLE)
@RequiredArgsConstructor
public class SimpleUserServiceImpl implements JapUserService {
    private final SysUserAccountMapper sysUserAccountMapper;

    /**
     * 用户名校验
     *
     * @param username 用户名
     * @return 用户信息
     */
    @Override
    public JapUser getByName(String username) {
        SysUserAccount sysUserAccount = sysUserAccountMapper.selectOne(Wrappers.lambdaQuery(new SysUserAccount())
                .eq(SysUserAccount::getSource, LoginSourceEnum.ACCOUNT)
                .eq(SysUserAccount::getUsername, username)
                .last("limit 1"));
        if (sysUserAccount == null) {
            return null;
        }
        return new JapUser().setUsername(sysUserAccount.getUsername()).setPassword(sysUserAccount.getPassword()).setUserId(sysUserAccount.getUserId().toString());
    }

    /**
     * 帐号密码登录
     *
     * @param password 密码
     * @param user     用户
     * @return true成功
     */
    @Override
    public boolean validPassword(String password, JapUser user) {
        boolean rst = user.getPassword().equals(SaSecureUtil.md5BySalt(password, BaseConstants.SALT));
        if (rst) {
            // 如果登录成功,保存uid到sa-token
            StpUtil.login(user.getUserId());
        }
        return rst;
    }

}